<?php
class AccountController extends ControllerBase {

	public function init(){
		Yii::app()->theme = SITE_THEME;
		$this->layout 		= '//layouts/full';
		$this->registerJs();
	}

	public function registerJs(){
		// Add mousewheel plugin (this is optional)
		Util::registerScriptFile(Util::themeUrl() . '/js/fancybox/jquery.mousewheel-3.0.6.pack.js', CClientScript::POS_HEAD);

		// Add fancyBox main JS and CSS files
		Util::registerScriptFile(Util::themeUrl() . '/js/fancybox/jquery.fancybox.js?v=2.0.6');
		Util::registerCssFile(Util::themeUrl().'/js/fancybox/jquery.fancybox.css?v=2.0.6','screen');


		if (isset($_GET['ajax']))
			$this->layout = '//layouts/blank';
	}
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return CMap::mergeArray(parent::filters(),array(
			'accessControl', // perform access control for CRUD operations
		));
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'users'=> Util::getMember(),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
    public function actionIndex() {
    	$memberId				= Yii::app()->user->id;
    	$member 				= $this->loadModel($memberId);
		$account				= $member->account;
		$donorVisit				= $member->donorvisitcount;

		$announcements			= Announcement::model()->getAsignByMember($memberId, 'asigned');
		$statistic['asigned']	= AnnouncementAssign::model()->countAsignByMember($memberId);
		$statistic['joined']	= AnnouncementAssign::model()->countAsignByMember($memberId, 'joined');
		$statistic['absence']	= $statistic['asigned'] - $statistic['joined'];
		list($codeActive, $edutionActive) = Util::getEducationInfo($member->membercode, false);
		$this->render('index', compact('statistic', 'announcements', 'courseActive', 'member', 'account', 'codeActive', 'edutionActive', 'donorVisit'));
    }

 	public function actionChangeAvatar() {
 		$member 	= $this->loadModel(Yii::app()->user->id);
 		$oldAvatar	= $member->avatar;
 		// Update profile
		if (isset($_FILES['avatar']['size']) && $_FILES['avatar']['size'] > 0) {
			$tmpNm				= time()-1;
			$imageName 			= strtolower($tmpNm . "." . Util::getFileExtension($_FILES['avatar']['name']));
			$member->avatar		= $imageName;
			move_uploaded_file($_FILES["avatar"]["tmp_name"], Util::pathUpload('profile') .'/' . $imageName);

			if (($oldAvatar != '') && file_exists(Util::pathUpload('profile') .'/' . $oldAvatar)) {
				unlink(Util::pathUpload('profile') .'/' . $oldAvatar);
			}

			$member->save();
		}
    }

	/**
	 * Change password for user
	 */
	public function actionChangepassword() {
		$model = new UserChangePassword;
		if (Yii::app()->user->id) {
			if(isset($_POST['UserChangePassword'])) {
				$model->attributes	= $_POST['UserChangePassword'];
				if($model->validate()) {
					$objAccount 					= User::model()->recover()->findbyPk(Yii::app()->user->id);
					$objAccount->password 			= UserModule::encrypting($model->password);
					$objAccount->recover_password 	= null;
					$objAccount->activkey			= UserModule::encrypting(microtime().$model->password);
					$objAccount->save();

					// Redirect to view
					$this->setFlash("Cập nhật thành công.");
					if (isset($_GET['ajax'])) {
						$this->printFlash();
						exit;
					} else {
						$this->redirect(array('index'));
					}
				}
			}
			$this->render('changepassword',array('model'=>$model));
	    }
	}
	public function actionEducation() {
		$membercode	= MemberCode::model()->getCode(Yii::app()->user->id);
		$education	= Education::model()->getEducation($membercode->code);
		list($semesters, $subjects) = Util::getSemesterInfo($education);
		$semester_delete = $subject_delete = null;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($member);
		if(isset($_POST['Semester'])) {
			// Get data post
			$semesters 				= $_POST['Semester'];
			$subjects 				= $_POST['Subject'];
			$subject_delete			= $_POST['subject_id_delete'];
			$semester_delete		= $_POST['semester_id_delete'];

			// Update semester and subject
			if (isset($semesters)) {
				foreach ($semesters as $index => $semester) {
					if (isset($semester['id'])) {
						$semesterModel	= Semester::model()->findByPk($semester['id']);
					}
					else {
						$semesterModel	= new Semester();
					}

					$semesterModel->attributes 		= $semester;
					$semesterModel->education_id	= $education->id;
					$semesterModel->save();

					// Update subject
					foreach ($subjects[$index] as $subject) {
						if (isset($subject['id'])) {
							$subjectModel	= Subject::model()->findByPk($subject['id']);
						}
						else {
							$subjectModel	= new Subject();
						}

						$subjectModel->attributes 		= $subject;
						$subjectModel->semester_id		= $semesterModel->id;
						$subjectModel->save();
					}
				}
			}

			// Delete subject
			if ($subject_delete != '') {
				$listSubjectDelete = explode(',' , $subject_delete);
				Subject::model()->deleteByPk($listSubjectDelete);
			}

			// Delete semester
			if ($semester_delete != '') {
				$listSemesterDelete = explode(',' , $semester_delete);
				Semester::model()->deleteByPk($listSemesterDelete);
			}

			// Redirect to view
			$this->setFlash("Cập nhật thành công.");
			if (isset($_GET['ajax'])) {
				$this->printFlash();
				exit;
			} else {
				$this->redirect(array('index'));
			}

		}

		$paramSemesterForm = array('semesters' => $semesters, 'subjects' => $subjects, 'subject_delete' => $subject_delete, 'semester_delete' => $semester_delete);
		$this->render('education', compact('education', 'membercode', 'paramSemesterForm'));
	}

	public function actionDonorVisit() {
		$donorvisit	= DonorVisit::model()->getVisit(Yii::app()->user->id);
		$visit_delete = null;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($member);
		if(isset($_POST['DonorVisit'])) {
			// Get data post
			$donorvisit 			= $_POST['DonorVisit'];
			$visit_delete			= $_POST['visit_id_delete'];

			// Update donor visit
			if (isset($donorvisit)) {
				foreach ($donorvisit as $index => $eachVisit) {
					if (isset($eachVisit['visit_id'])) {
						$donorvisitModel	= DonorVisit::model()->findByPk($eachVisit['visit_id']);
					}
					else {
						$donorvisitModel	= new DonorVisit();
					}
					$donorvisitModel->attributes = $eachVisit;
					$donorvisitModel->member_id	 = Yii::app()->user->id;
					$donorvisitModel->save();
				}
			}
			// Delete visit
			if ($visit_delete != '') {
				$listVisitDelete = explode(',' , $visit_delete);
				DonorVisit::model()->deleteByPk($listVisitDelete);
			}

			// Redirect to view
			$this->setFlash("Cập nhật thành công.");
			if (isset($_GET['ajax'])) {
				$this->printFlash();
				exit;
			} else {
				$this->redirect(array('index'));
			}

		}

		$paramDonorVisitForm = array('donorvisit' => $donorvisit, 'visit_delete' => $visit_delete);
		$this->render('donorvisit', compact('paramDonorVisitForm'));
	}

	/**
	 * Updates a particular model.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionProfile() {
		$userId		= Yii::app()->user->id;
		$member		= Member::model()->findByPk($userId);
		$account	= $member->account;

		// Get old avatar
		$oldAvatar	= $member->avatar;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($member);
		if(isset($_POST['Member'])) {
			// Get data post
			$member->attributes		= $_POST['Member'];

			// Connvert string to lowercase
			$member->fullname		= Util::formatFullName($member->fullname, true);
			// Clear all character non numberic
			$inputPhone				= $member->phone;
			$inputCellPhone			= $member->cellphone;
			$member->phone			= Util::formatPhone($inputPhone, false);
			$member->cellphone		= Util::formatPhone($inputCellPhone, false);

			$validMember	= $member->validate();

			if($validMember) {
				// Update account
				$account->email	= $member->email;
				$account->update();
				$member->save();

				// Redirect to view
				$this->setFlash("Cập nhật thành công.");
				if (isset($_GET['ajax'])) {
					$this->printFlash();
					exit;
				} else {
					$this->redirect(array('index'));
				}
			}

			$member->phone		= $inputPhone;
			$member->cellphone	= $inputCellPhone;
		}

		$this->render('profile', compact('member', 'account'));
	}

	public function actionReloadEducation(){
		$membercode	= MemberCode::model()->getCode(Yii::app()->user->id);
		$education	= Education::model()->getEducation($membercode->code);
		echo $this->widget('SemesterView', array('education' => $education, 'current' => true), true);
		exit;
	}

	public function actionReloadDonorVisit(){
    	$member 				= $this->loadModel(Yii::app()->user->id);
		$donorVisit				= $member->donorvisitcount;
		echo $donorVisit;
		exit;
	}

	public function actionReloadProfile(){
		$member				= Member::model()->findByPk(Yii::app()->user->id);
		$profile['info']	= $this->widget('ProfileView', array('member' => $member, 'type' => 'profile'), true);
		$profile['social']	= $this->widget('ProfileView', array('member' => $member, 'type' => 'social'), true);
		echo json_encode($profile);
		exit;
	}
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Member::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
}